package com.example.backend.util;

import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * 输入验证工具类
 */
@Component
public class ValidationUtil {
    
    // 用户名正则：3-20个字符，只能包含字母、数字和下划线
    private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_]{3,20}$");
    
    // 密码正则：至少6个字符，必须包含大小写字母和数字
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d@$!%*?&]{6,}$");
    
    // 邮箱正则
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
    
    // 手机号正则（中国大陆）
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    
    /**
     * 验证用户名
     */
    public boolean isValidUsername(String username) {
        return username != null && USERNAME_PATTERN.matcher(username).matches();
    }
    
    /**
     * 验证密码强度
     */
    public boolean isValidPassword(String password) {
        return password != null && PASSWORD_PATTERN.matcher(password).matches();
    }
    
    /**
     * 验证邮箱格式
     */
    public boolean isValidEmail(String email) {
        return email != null && EMAIL_PATTERN.matcher(email).matches();
    }
    
    /**
     * 验证手机号格式
     */
    public boolean isValidPhone(String phone) {
        return phone == null || phone.isEmpty() || PHONE_PATTERN.matcher(phone).matches();
    }
    
    /**
     * 验证真实姓名
     */
    public boolean isValidFullName(String fullName) {
        return fullName != null && fullName.trim().length() >= 2 && fullName.trim().length() <= 50;
    }
    
    /**
     * 检查密码是否包含常见弱密码
     */
    public boolean isWeakPassword(String password) {
        if (password == null) return true;
        
        String[] weakPasswords = {
            "password", "123456", "123456789", "qwerty", "abc123",
            "password123", "admin", "root", "user", "test"
        };
        
        String lowerPassword = password.toLowerCase();
        for (String weak : weakPasswords) {
            if (lowerPassword.contains(weak)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 检查用户名是否包含敏感词
     */
    public boolean containsSensitiveWords(String text) {
        if (text == null) return false;
        
        String[] sensitiveWords = {
            "admin", "root", "system", "test", "demo", "guest"
        };
        
        String lowerText = text.toLowerCase();
        for (String word : sensitiveWords) {
            if (lowerText.contains(word)) {
                return true;
            }
        }
        
        return false;
    }
}
